<template>
  <div>
    <el-button type="primary" @click="showAdd = true">添加慢病</el-button>
    <el-table :data="chronicList" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="ID" width="60"/>
      <el-table-column prop="userName" label="用户"/>
      <el-table-column prop="diseaseName" label="疾病名称"/>
      <el-table-column prop="diagnosis" label="诊断信息"/>
      <el-table-column prop="status" label="状态"/>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="editChronic(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteChronic(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="showAdd" title="慢病信息">
      <el-form :model="form">
        <el-form-item label="用户"><el-input v-model="form.userName"/></el-form-item>
        <el-form-item label="疾病名称"><el-input v-model="form.diseaseName"/></el-form-item>
        <el-form-item label="诊断信息"><el-input v-model="form.diagnosis"/></el-form-item>
        <el-form-item label="状态"><el-input v-model="form.status"/></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAdd = false">取消</el-button>
        <el-button type="primary" @click="saveChronic">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCurrentUserDiseasesApi, addChronicApi, updateChronicDiseaseApi, deleteChronicDiseaseApi } from '../api/chronic'

const chronicList = ref([])
const showAdd = ref(false)
const isEdit = ref(false)
const chronicForm = reactive({})

const loadChronics = async () => {
  try {
    const res = await getCurrentUserDiseasesApi()
    if (res.code === 200) {
      chronicList.value = res.data
    } else {
      ElMessage.error(res.message || '获取慢性病列表失败')
    }
  } catch (error) {
    console.error('获取慢性病列表失败:', error)
    ElMessage.error('获取慢性病列表失败，请重试')
  }
}

const saveChronic = async () => {
  try {
    const res = isEdit.value ? await updateChronicDiseaseApi(chronicForm.id, chronicForm) : await addChronicApi(chronicForm)
    if (res.code === 200) {
      ElMessage.success(isEdit.value ? '慢性病信息更新成功' : '慢性病信息添加成功')
      showAdd.value = false
      loadChronics()
    }
  } catch (error) {
    console.error('保存慢性病信息失败:', error)
    ElMessage.error('保存慢性病信息失败，请重试')
  }
}

const editChronic = (row) => {
  chronicForm = { ...row }
  isEdit.value = true
  showAdd.value = true
}

const deleteChronic = async (id) => {
  try {
    const res = await deleteChronicDiseaseApi(id)
    if (res.code === 200) {
      ElMessage.success('慢性病信息删除成功')
      loadChronics()
    }
  } catch (error) {
    console.error('删除慢性病信息失败:', error)
    ElMessage.error('删除慢性病信息失败，请重试')
  }
}

onMounted(loadChronics)
</script> 